import requests
import json
import re
import sqlite3
import time


class ETHHASH:
    def get_hash(self, hash_num):
        """
        根据hash块高实时知道开出的块
        :param hash_num:
        :return:
        """
        url = 'https://api.yitaifang.com/index/header/?number=' + str(hash_num)
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/51.0.2704.63 Safari/537.36'}
        r = requests.get(url, headers=headers, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        arr_data = json.loads(r.text)
        if arr_data["code"] == 10000:
            str_hash = arr_data["data"]["hash"]
            str_time = arr_data["data"]["timestamp"]
            str_num = re.sub('\D', '', str_hash)[-2:]
            print(hash_num)
            self.write_db(hash_num, str_num, str_time)

    def write_db(self, hash_num, num, int_time):
        """
        写入数据库
        :param hash_num:
        :param num:
        :param int_time:
        :return:
        """
        conn = sqlite3.connect('J:\\WORK\\hash\\db\\hash.db')
        c = conn.cursor()
        c.execute("INSERT INTO HASH (BLOCK, NAME, TIME) VALUES " + "(" + str(hash_num) + "," + str(num) + "," + str(int_time) + ")")
        conn.commit()
        conn.close()

    def get_db(self):
        """
        拿到数据库中所有的hash块
        :return:
        """
        conn = sqlite3.connect('J:\\WORK\\hash\\db\\hash.db')
        c = conn.cursor()
        cursor = c.execute("SELECT ID, BLOCK, NAME, TIME FROM (SELECT ID, BLOCK, NAME, TIME from HASH ORDER BY ID DESC limit 0,100) a ORDER  BY ID")
        arr_hash = []
        for row in cursor:
            arr_hash.append({
                "id": row[0],
                "height": row[1],
                "hash": row[2],
                "time": row[3]
            })
        conn.close()
        return arr_hash

    def init_db(self):
        """
        初始化数据
        :return:
        """
        conn = sqlite3.connect('J:\\WORK\\hash\\db\\hash.db')
        c = conn.cursor()
        c.execute('''CREATE TABLE HASH
               (ID INTEGER PRIMARY KEY AUTOINCREMENT,
               BLOCK          INT      NOT NULL, 
               NAME           TEXT     NOT NULL, 
               TIME           TEXT    NOT NULL);''')
        conn.commit()
        conn.close()

    def set_time_out_get_hash(self):
        """
        定时每一秒执行一次，获取hash，有则插入数据库
        :return:
        """
        while True:
            # 先去数据库获取最新的100条数据
            arr_hash_100 = self.get_db()
            # 取最新的一条数据的块高，再获取最新数据块高加10的数据的hash值
            print(len(arr_hash_100))
            print(arr_hash_100)
            print(arr_hash_100[-1:])
            print(arr_hash_100[-1:][0]["hash"])
            print(arr_hash_100[-1:][0]["height"])
            self.get_hash(arr_hash_100[-1:][0]["height"] + 10)
            time.sleep(1)

    def do_it(self):
        """
        开始执行
        :return:
        """
        for i in range(8593530, 8597521):
            if i % 10 == 0:
                self.get_hash(i)
                time.sleep(1)


app = ETHHASH()
app.set_time_out_get_hash()